<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;

use think\Session;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;
/**
 * 维修记录管理
 *
 * @icon fa fa-circle-o
 */
class Maintenance extends Backend
{
    
    /**
     * Maintenance模型对象
     * @var \app\admin\model\jdy\Maintenance
     */
    protected $model = null;
    protected $multiFields = 'switch';

    protected $noNeedRight = ['add2', 'add3', 'index2', 'daping1', 'daping2', 'importnew'];

    const TASK_ID = "__maintenancetaskid__";
    const ANCHANG_ID = "__maintenanceanchangid__";

    protected $iskehu = false;//客户不能看一些记录
    protected $isadmin = false;//

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Maintenance;

        $zhuguan = 0;//$this->auth->check('dahui/dingdan/audit')
        $group_ids = $this->auth->getGroupIds();
        if (in_array("2", $group_ids) || in_array("8", $group_ids) || in_array("1", $group_ids)) {
            $zhuguan = 1;
        }
        $this->assignconfig('zhuguan', $zhuguan);

        if (in_array("5", $group_ids) || in_array("9", $group_ids) ) {
            $this->iskehu = true;
        }
        $this->assignconfig('iskehu', $this->iskehu);

        if (in_array("2", $group_ids) || in_array("1", $group_ids)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $anchang_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        $anchangname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;

                Session::set(self::ANCHANG_ID, $anchang_id);
                Session::delete(self::TASK_ID, '');
            }
        } else {
            Session::set(self::ANCHANG_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $where1 = "";
            if (isset($filter['keywords'])) {
                $keywords = $filter['keywords'];
                $where1 = " (`maintenance`.`content` like '%".$keywords."%' or `maintenance`.`message` like '%".$keywords."%')";
            }
            if (isset($filter['create_time'])) {
                $times = explode(' - ', $filter['create_time']);
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`create_time` >= '" . $times[0] . "' and `maintenance`.`create_time` <= '" . $times[1] . "'";
            }
            if (isset($filter['anchang.name'])) {
                $keywords = $filter['anchang.name'];
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `anchang`.`name` like '%" . $keywords . "%'";
            }

            if (isset($filter['switch'])) {
                $switch = $filter['switch'];
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`switch` = " . $switch ;
            }
            if ($anchang_id > 0) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`anchang_id` = " . $anchang_id;
            } else {
                $anchangids = $this->getanchangids();

                if (!$this->isadmin) {
                    if (!empty($where1)) {
                        $where1 .= " and ";
                    }
                    if (empty($anchangids)) {
                        $where1 .= " maintenance.anchang_id  = 0 ";
                    } else {
                        $where1 = " maintenance.anchang_id in (" . $anchangids . ") ";
                    }
                }
            }

            if ($this->iskehu) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }

                $where1 .= " maintenance.switch = 1";
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['anchang', 'task'])
                ->where($where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['anchang', 'task'])
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("iskehu", $this->iskehu);

        return $this->view->fetch();
    }

    /**
     * 查看 from task
     */
    public function index2()
    {
        $task_id = 0;
        $anchang_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        $anchangname = "";
        $taskname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $task_id = $urls[$size - 1];
            Session::set(self::TASK_ID, $task_id);
            Session::set(self::ANCHANG_ID, 0);

            $task = \app\admin\model\jdy\Task::get($task_id);
            if ($task) {
                $taskname = $task->title;
                $anchang = \app\admin\model\jdy\Anchang::get($task->anchang_id);
                if ($anchang) {
                    $anchangname = $anchang->name;
                }
            }
        } else {
            Session::set(self::ANCHANG_ID, 0);
            Session::set(self::TASK_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $where1 = "";
            if (isset($filter['keywords'])) {
                $keywords = $filter['keywords'];
                $where1 = " (`maintenance`.`content` like '%".$keywords."%' or `maintenance`.`message` like '%".$keywords."%')";
            }
            if (isset($filter['create_time'])) {
                $times = explode(' - ', $filter['create_time']);
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`create_time` >= '" . $times[0] . "' and `maintenance`.`create_time` <= '" . $times[1] . "'";
            }
            if (isset($filter['anchang.name'])) {
                $keywords = $filter['anchang.name'];
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `anchang`.`name` like '%" . $keywords . "%'";
            }

            if (isset($filter['switch'])) {
                $switch = $filter['switch'];
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`switch` = " . $switch ;
            }
            if ($task_id > 0) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`task_id` = " . $task_id;
            } else if ($anchang_id > 0) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " `maintenance`.`anchang_id` = " . $anchang_id;
            } else {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $anchangids = $this->getanchangids();

                if (!$this->isadmin) {
                    if (empty($anchangids)) {
                        $where1 .= " maintenance.anchang_id  = 0 ";
                    } else {
                        $where1 = " maintenance.anchang_id in (" . $anchangids . ") ";
                    }
                }

            }

            if ($this->iskehu) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                $where1 .= " maintenance.switch = 1";
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['anchang', 'task'])
                ->where($where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['anchang', 'task'])
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {


            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("taskname", $taskname);
        $this->view->assign("iskehu", $this->iskehu);

        return $this->view->fetch();
    }

    function getadminnickname($adminid)
    {
        $admin = \app\admin\model\Admin::get($adminid);
        if ($admin) {
            return $admin->nickname;
        }

        return "";
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['luruman'] = $this->auth->nickname;
                    $result = $this->model->allowField(true)->save($params);
                    $this->savetask($this->model);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $task_id = Session::get(self::TASK_ID);
        $task = \app\admin\model\jdy\Task::get($task_id);
        $anchang_id = 0;
        $price = 0;
        if ($task) {
            //--不应该进来
            $anchang_id = $task->anchang_id;
            $price = $task->price;
            $this->view->assign("anchang_id", $anchang_id);
            $this->view->assign("task_id", $task_id);
        } else {
            $anchang_id = Session::get(self::ANCHANG_ID);
            $this->view->assign("anchang_id", $anchang_id);
            $this->view->assign("task_id", 0);
        }
        $this->view->assign("luruman", $this->auth->nickname);
        $this->view->assign("content0", $this->getcontent0($anchang_id));
        $this->view->assign("price", $price);
        $this->view->assign("content1", date("Y-m-d") . " " . $this->auth->nickname . " ");

        return $this->view->fetch();
    }

    function getcontent0($anchang_id)
    {
        $content0 = "";
        $list = $this->model
            ->where('anchang_id', $anchang_id)
            ->field('content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        foreach ($list as $row) {
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= $row->create_time . "\n录入人員:" .$row->luruman. "\n内容:" . $row->content . "\n主管留言:" . $message . "\n\n";
        }

        return $content0;
    }

    function getcontent1($anchang_id, $task_id)
    {
        $content0 = "";
        $list = $this->model
            ->where('anchang_id', $anchang_id)
            ->where('task_id', $task_id)
            ->field('content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        foreach ($list as $row) {
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= $row->create_time . "\n录入人員:" .$row->luruman. "\n内容:" . $row->content . "\n主管留言:" . $message . "\n\n";
        }

        return $content0;
    }


    //从案场添加
    public function add2()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['luruman'] = $this->auth->nickname;
                    $result = $this->model->allowField(true)->save($params);

                    $this->savetask($this->model);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $anchang_id = Session::get("__taskanchangid__");
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("task_id", 0);
        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
        $anchangname = "";
        if ($anchang) {
            $anchangname = $anchang->name;
        }
        $this->view->assign("anchangname", $anchangname);

        $this->view->assign("content0", $this->getcontent0($anchang_id));
        $this->view->assign("luruman", $this->auth->nickname);
        $this->view->assign("content1", date("Y-m-d") . " " . $this->auth->nickname . ":\n");

        return $this->view->fetch();
    }

    //task关联添加
    public function add3($ids)
    {
        $task_id = $ids;
        $anchang_id = 0;
        $anchangname = "";
        $taskname = "";
        $task = \app\admin\model\jdy\Task::get($task_id);
        if ($task) {
            $taskname = $task->title;
            $anchang_id = $task->anchang_id;
            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['luruman'] = $this->auth->nickname;

                    if ($task) {
                        if ($task->images != $params['images']) {
                            $params['content'] .= " [增加工作圖片]";
                        }
                        //[標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
                        $params['content'] = "[標題: {$task['title']}][提醒日期: {$params['remind_date']}][提醒狀態: {$params['task_status']}][內容: {$params['content']}]";
                    }

                    $result = $this->model->allowField(true)->save($params);
                    unset($params['content']);
                    $task->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (!$task) {
            $this->error(__('无此工作事项！'));
        }


        $acdevices = "";
        $lista = \app\admin\model\jdy\Acdevice::where('id', 'in', $task['acdevice_ids'])->field('name')->select();
        foreach ($lista as $rowa) {
            $acdevices .= $rowa->name . ",";
        }

        $this->view->assign("acdeviceparams", '{"custom[anchang_id]":"' . $anchang_id . '"}');

        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("task_id", $task_id);
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("taskname", $taskname);
        $this->view->assign("content0", $this->getcontent1($anchang_id, $task_id));
        $this->view->assign("luruman", $this->auth->nickname);
        $this->view->assign("acdevices", $acdevices);
        $this->view->assign("content1", date("Y-m-d") . " " . $this->auth->nickname . " ");
        $price = $task->price;
        $this->view->assign("price", $price);

        $this->view->assign("taskStatusList", $task->getTaskStatusList());

        $task = $task->toArray();
        $this->view->assign("task", $task);


        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (isset($params['message'])) {
                        $params['managerman'] = $this->auth->nickname;
                    } else {
                        $params['luruman'] = $this->auth->nickname;
                    }
                    $result = $row->allowField(true)->save($params);
                    $this->savetask($row);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $anchang = \app\admin\model\jdy\Anchang::get($row->anchang_id);
        $anchangname = "";
        if ($anchang) {
            $anchangname = $anchang->name;
        }

        $task_id = $row->task_id;
        $taskname = "";
        $task = \app\admin\model\jdy\Task::get($task_id);
        if ($task) {
            $taskname = $task->title;
        }

        $this->view->assign("row", $row);
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("taskname", $taskname);
        $this->view->assign("luruman", $this->auth->nickname);

        $anchang_id = $row->anchang_id;
        //->where('create_time', '<', $row->create_time)  是否要去除编辑项
        $this->view->assign("content0", $this->getcontent0($anchang_id));

        $price = $row->price;
        $this->view->assign("price", $price);

        return $this->view->fetch();
    }

    public function savetask($maintenance)
    {
        if (!$maintenance) {
            return;
        }

        $task = \app\admin\model\jdy\Task::get($maintenance->task_id);
        if ($task) {
            $task->price = $maintenance->price;
            $task->save();
        }

    }

    //获取账号关联的案场ids
    public function getanchangids()
    {
        $anchangidlist = json_decode($this->auth->anchangids, TRUE);
        $xianshi = [];
        $xianshi[] = $this->auth->xianshi1;
        $xianshi[] = $this->auth->xianshi2;
        $xianshi[] = $this->auth->xianshi3;
        $xianshi[] = $this->auth->xianshi4;
        $xianshi[] = $this->auth->xianshi5;

        $xzq = [];
        $xzq[] = $this->auth->xzq1;
        $xzq[] = $this->auth->xzq2;
        $xzq[] = $this->auth->xzq3;
        $xzq[] = $this->auth->xzq4;
        $xzq[] = $this->auth->xzq5;

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $amodel = new \app\admin\model\jdy\Anchang;
        $list = $amodel
            ->where($whereA)
            ->field('id')
            ->select();

        $anchangids = "";
        foreach ($list as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }

        return $anchangids;
    }

    /**
     * 维修记录主管检视
     */
    public function daping1()
    {
        $title = "维修记录检视";
        $this->view->assign([
            'title' => $title
        ]);

        $anchang_id = 0;

        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];
        } else {
            $url = $_SERVER['REQUEST_URI'];
        }

        $anchangname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }

        $list = $this->model
            ->with(['task'])
            ->where('maintenance.anchang_id', $anchang_id)
            ->field('maintenance.content, maintenance.message, maintenance.switch, maintenance.create_time, maintenance.luruman, task.title')
            ->order("create_time desc")
            ->select();

        foreach ($list as &$row) {
            if (!$row->message) {
                $row->message = "";
            }
            $content1 = date("Y-m-d", strtotime($row->create_time)) . " " . $row->luruman;
            if (!$row->content || strpos($row->content, $content1) === false) {
                $row->content = $content1." ".$row->content;
            }
        }

        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    /**
     * 维修记录客户公告
     */
    public function daping2()
    {
        $title = "维修记录检视";
        $this->view->assign([
            'title' => $title
        ]);

        $anchang_id = 0;
        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];
        } else {
            $url = $_SERVER['REQUEST_URI'];
        }
        $anchangname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }

        $list = $this->model
            ->with(['task'])
            ->where('maintenance.anchang_id', $anchang_id)
            ->where('switch', 1)
            ->field('maintenance.content, maintenance.message, maintenance.switch, maintenance.create_time, maintenance.luruman, task.title')
            ->order("create_time desc")
            ->select();

        foreach ($list as &$row) {
            if (!$row->message) {
                $row->message = "";
            }
            $content1 = date("Y-m-d", strtotime($row->create_time)) . " " . $row->luruman;
            if (!$row->content || strpos($row->content, $content1) === false) {
                $row->content = $content1.": ".$row->content;
            }
        }

        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    //http://acciot.test/admin/jdy/maintenance/importnew
    //导出
    public function importnew()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);

        $anchang_id = Session::get(self::ANCHANG_ID);
        if (!$anchang_id) {
            $anchang_id = 0;
        }

        $where1 = "";
        if (isset($filter['keywords'])) {
            $keywords = $filter['keywords'];
            $where1 = " (`maintenance`.`content` like '%".$keywords."%' or `maintenance`.`message` like '%".$keywords."%')";
        }
        if (isset($filter['create_time'])) {
            $times = explode(' - ', $filter['create_time']);
            if (!empty($where1)) {
                $where1 .= " and ";
            }
            $where1 .= " `maintenance`.`create_time` >= '" . $times[0] . "' and `maintenance`.`create_time` <= '" . $times[1] . "'";
        }
        if (isset($filter['anchang.name'])) {
            $keywords = $filter['anchang.name'];
            if (!empty($where1)) {
                $where1 .= " and ";
            }
            $where1 .= " `anchang`.`name` like '%" . $keywords . "%'";
        }

        if (isset($filter['switch'])) {
            $switch = $filter['switch'];
            if (!empty($where1)) {
                $where1 .= " and ";
            }
            $where1 .= " `maintenance`.`switch` = " . $switch ;
        }
        if ($anchang_id > 0) {
            if (!empty($where1)) {
                $where1 .= " and ";
            }
            $where1 .= " `maintenance`.`anchang_id` = " . $anchang_id;
        } else {
            $anchangids = $this->getanchangids();

            if (!$this->isadmin) {
                if (!empty($where1)) {
                    $where1 .= " and ";
                }
                if (empty($anchangids)) {
                    $where1 .= " maintenance.anchang_id  = 0 ";
                } else {
                    $where1 = " maintenance.anchang_id in (" . $anchangids . ") ";
                }
            }
        }

        if ($this->iskehu) {
            if (!empty($where1)) {
                $where1 .= " and ";
            }

            $where1 .= " maintenance.switch = 1";
        }

        $count = $this->model
            ->with(['anchang', 'task'])
            ->where($where1)->count();


        set_time_limit(0);
        ini_set('memory_limit', '128M');

        header('Content-Type: application/vnd.ms-execl');
        header('Content-Disposition: attachment;filename="維修紀錄.csv"');

        //打开php标准输出流
        //以写入追加的方式打开
        $fp = fopen('php://output', 'a');
        //一次取5000条数据
        $step = ceil($count/5000);

//        $chartset = 'GBK';//'GBK';//BIG5
//        $title = array(
//            iconv('UTF-8', $chartset, '创建时间'),
//            iconv('UTF-8', $chartset, '案場名称'),
//            iconv('UTF-8', $chartset, '标题'),
//            iconv('UTF-8', $chartset, '内容'),
//            iconv('UTF-8', $chartset, '主管留言'),
//            iconv('UTF-8', $chartset, '录入人員'),
//        );
        $title = array(
            mb_convert_encoding('創建時間', 'BIG5', 'UTF-8'),
            mb_convert_encoding('案場名稱', 'BIG5', 'UTF-8'),
            mb_convert_encoding('標題', 'BIG5', 'UTF-8'),
            mb_convert_encoding('內容', 'BIG5', 'UTF-8'),
            mb_convert_encoding('主管留言', 'BIG5', 'UTF-8'),
            mb_convert_encoding('錄入人員', 'BIG5', 'UTF-8'),
        );

        //将标题写到标准输出中
        fputcsv($fp, $title);

        for($s = 0; $s < $step; $s++) {
            $page_count = $s;
            $page_size = 5000;
            $offset = $page_count * $page_size;

            $list = $this->model
                ->with(['anchang', 'task'])
                ->where($where1)
                ->limit($offset, $page_size)
                ->select();

            $data = collection($list)->toArray();

            foreach ($data as &$row) {
                try {
                    $row['anchangname'] = mb_convert_encoding($row['anchang']['name'], 'BIG5', 'UTF-8');
                    $row['tasktitle'] = mb_convert_encoding($row['task']['title'], 'BIG5', 'UTF-8');
                    if (!empty($row['content'])) {
                        $row['content'] = mb_convert_encoding($row['content'], 'BIG5', 'UTF-8');
                    }
                    if (empty($row['message'])) {
                        $row['message'] = mb_convert_encoding($row['message'], 'BIG5', 'UTF-8');
                    }

                    $row['luruman'] = mb_convert_encoding($row['luruman'], 'BIG5', 'UTF-8');
                    $v = array(
                        $row['create_time'],
                        $row['anchangname'],
                        $row['tasktitle'],
                        $row['content'],
                        $row['message'],
                        $row['luruman']
                    );

                    fputcsv($fp, $v);
                } catch (\Exception $e) {
                    continue;
                }
            }

            //每5000条数据就刷新缓冲区
            ob_flush();
            flush();
        }
        exit();

    }


}
